package com.situ.allaia.api;

import com.situ.allaia.model.Good;
import com.situ.allaia.model.GoodSearchBean;
import com.situ.allaia.service.GoodService;
import com.situ.allaia.util.PaginateInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/goods", produces = "application/json;charset=utf-8")
public class GoodApi {
    private final GoodService goodService;

    public GoodApi(GoodService goodService) {
        this.goodService = goodService;
    }


    @GetMapping
    public Map<String, Object> findAll(GoodSearchBean gsb,
                                       @RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "10") Integer limit) {
        PaginateInfo pi = new PaginateInfo(page, limit);
        List<Good> goods = goodService.findAll(gsb, pi);

        return Map.of("code", 0, "count", pi.getTotal(), "data", goods);
    }

    @PostMapping
    public Map<String, Object> add(Good good) {
        //todo:参数校验
        if (!StringUtils.hasText(good.getName())) {
            return Map.of("success", false, "error", "商品名称不可为空");
        }

        boolean success = goodService.save(good);
        return Map.of("success", success, "data", good);
    }

    @PutMapping
    public Map<String, Object> edit(Good good) {
        //todo:参数校验
        if (!StringUtils.hasText(good.getName())) {
            return Map.of("success", false, "error", "商品名称不可为空");
        }

        boolean success = goodService.update(good);//部分修改

        return Map.of("success", success, "data", good);
    }

    @PatchMapping("/takeoff")
    public Map<String, Object> takeOff(Good good) {
        boolean b = goodService.patch(good);
        return Map.of("success", b);
    }
    @PatchMapping("/bestseller")
    public Map<String, Object> bestSeller(Good good) {
        boolean b = goodService.patch(good);
        return Map.of("success", b);
    }
    @PatchMapping("/newproduct")
    public Map<String, Object> newProduct(Good good) {
        boolean b = goodService.patch(good);
        return Map.of("success", b);
    }

    @DeleteMapping
    public Map<String, Object> deleteByIds(Integer[] ids) {
        int rows = goodService.deleteByIds(List.of(ids));
        return Map.of("success", rows > 0, "rows", rows);
    }
}
